package 代码随想录_回溯.棋盘问题;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zx
 * @create 2022-06-11 17:16
 */
public class n皇后_51 {
    /**
     * 思路来源于代码随想录,官方太难理解了
     */
    List<List<String>> res = new ArrayList<>();
    public List<List<String>> solveNQueens(int n) {
        char[][] chessboard = new char[n][n];
        for(int i = 0;i < n;i++){
            for(int j = 0;j < n;j++){
                chessboard[i][j] = '.';
            }
        }
        dfs(n,0,chessboard);
        return res;
    }
    private void dfs(int n,int row,char[][] chessboard){
        if(row == n){
            res.add(newBoard(chessboard));//注意这里
            return;
        }
        for (int col = 0; col < n; ++col) {
            if (isValid(row, col, n, chessboard)) {
                chessboard[row][col] = 'Q';//放置皇后
                dfs(n, row + 1, chessboard);
                chessboard[row][col] = '.';//回溯,撤销皇后
            }
        }
    }
    public boolean isValid(int row, int col, int n, char[][] chessboard) {
        // 检查列
        for (int i = 0; i < row; ++i) { // 相当于剪枝
            if (chessboard[i][col] == 'Q') {
                return false;
            }
        }
        // 检查45度对角线
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }
        // 检查135度对角线
        for (int i = row - 1, j = col + 1; i >= 0 && j <= n - 1; i--, j++) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }
    public List<String > newBoard(char[][] chessboard) {
        List<String> list = new ArrayList<>();
        for (char[] c : chessboard) {
            list.add(new String(c));
        }
        return list;
    }
}
